import { NzModalService } from 'ng-zorro-antd/modal';
import { BaseService } from '@service/base.service';
import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder } from '@angular/forms';
import { IBaseArea } from '@model/base';
import { BaseAreaEditComponent } from './base-area-edit/base-area-edit.component';
import { AuthService } from '@service/auth.service';
const ID = '123456789';

@Component({
	selector: 'app-base-area',
	templateUrl: './base-area.component.html',
	styleUrls: ['./base-area.component.less']
})
export class BaseAreaComponent extends AbsFormUtil implements OnInit {

	nzLoading = false;
	data = [];

	constructor(
		private baseService: BaseService,
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private nzModalService: NzModalService,
		private authService: AuthService
	) {
		super();
	}

	ngOnInit() {
		this.buildForm();
		this.onSearch();
		this.authList = this.authService.getAuth();

	}
	buildForm() {
		this.validateForm = this.fb.group({
			gridAreaName: ['']
		});
	}

	async onSearch(isPageInit?: boolean) {
		this.nzLoading = true;
		if (isPageInit) {
			this.page.page = 1;
		}
		const params = { ...this.validateForm.value, ...this.page };
		const result = await this.baseService.getGridAreaList(params);
		this.data = result.data.list;
		this.page.total = result.data.totalCount;
		this.nzLoading = false;
	}


	async del(item: IBaseArea) {
		const result = await this.baseService.deleteGridArea(item.id);
		this.nzMessageService.success('删除成功');
		const idx = this.data.findIndex(it => it.id === item.id);
		this.data.splice(idx, 1);
		this.data = [...this.data];
	}

	



	add(item?: IBaseArea) {
		this.nzModalService.create({
			nzTitle: item ? '编辑网格' : '新增网格',
			nzContent: BaseAreaEditComponent,
			nzBodyStyle: {
				padding: '10px 20px'
			},
			nzWidth: '70%',
			nzComponentParams: {
				id: item?.id
			},
			nzFooter: [
				{
					label: '确定',
					type: 'primary',
					onClick: (componentInstance) => {
						(async () => {
							const resForm = componentInstance.onSubmit() as any;
							if (resForm) {
								const id = componentInstance.id || ''
								resForm.id = id;
								resForm.ownerCommunity = resForm.ownerCommunity[resForm.ownerCommunity.length - 1];
								const result = await this.baseService.saveGridArea(resForm);
								if (result.status !== 0) {
									this.nzMessageService.error(result.msg || '保存失败');
									return;
								}
								componentInstance.destroyModal();
								this.onSearch(true);
								this.nzMessageService.success('保存成功');
							}
						})();
					}
				},
				{
					label: '取消',
					onClick: componentInstance => {
						componentInstance.destroyModal();
					}
				}
			]
		})
	}


}
